package spe.ui.editor.command;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.commands.Command;

import spe.model.notation.Link;
import spe.model.spem.MethodPlugin;
import spe.model.spem.NodeElement;

public class LinkCreateLinkCommand extends Command 
{
	private NodeElement source;
	private NodeElement target;
	
	private Link link;
	
	public void setTarget(NodeElement tgt)
	{
		target = tgt;
	}
	
	public void setSource(NodeElement src)
	{
		source = src;
	}
	
	public void setLink(Link l)
	{
		link = l;
	}
	
	@Override
	public boolean canExecute()
	{
		return (source!=null) && (target != null);
	}
	
	@Override
	public void execute()
	{
		if(source == target && link.getBendPoints().isEmpty())
			addPendPoints();
		
		source.addLeavingEdge(link);
		target.addArrivingEdge(link);
		
		//test
		if(MethodPlugin.class.isInstance(source) && MethodPlugin.class.isInstance(target))
		{
			link.setConnectionType(Link.EXTENDED);
			((MethodPlugin)source).setBasePlugin((MethodPlugin) target);
		}
		//////////////////////////
		
		source.firePropertyChange("Link", link, "");
		target.firePropertyChange("Link", link, "");
	}
	
	
	private void addPendPoints()
	{
		Point constraint = source.getPosition();
		int horizontal = - (/*icon width*/ 32 / 2 + 25);
		int vertical = horizontal; //* constraint.height / constraint.width;
		Point first = new Point(horizontal, vertical);
		link.addBendPoint(first);
	}
}
